package com.ahui.service.impl;

import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.ahui.domain.ResultDataFGKDZ;
import com.ahui.handler.FileHandler;
import com.ahui.handler.FileHandlerFactory;
import com.ahui.service.FGKDZSevervice;
import com.ahui.util.ExcelUtil;
import com.ahui.util.FileUtil;
import com.ahui.util.PdfUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * @author : ph.li
 * @date : 2023/9/1 18:05
 */
@Service
@Slf4j
public class FGKDZServiceImpl implements FGKDZSevervice {

    // 非公开定增测试
    public void toexcel() {
        String inputPath = "E:\\文档\\工作\\致宇\\兴证全球\\数据处理\\9.1统计结果\\兴全-缴款通知书    非公开定增";
        String outputPath = "E:\\文档\\工作\\致宇\\兴证全球\\数据处理\\9.1统计结果\\run-imag";
        String exportPath = "E:\\文档\\工作\\致宇\\兴证全球\\数据处理\\9.1统计结果\\run-excel\\交易申请单.xlsx";
        String copyPath = "E:\\文档\\工作\\致宇\\兴证全球\\数据处理\\9.1统计结果\\run-file";

        // 根据路径读取该路径下的所有文件
        List<File> fileList = FileUtil.getFiles(inputPath);
        Collections.sort(fileList);
        List<ResultDataFGKDZ> resultList = new ArrayList<>();
        File copyPathFile = new File(copyPath);
        // 循环处理tif文件
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < fileList.size(); i++) {
            log.info("=================开始处理第{}个文件===================", (i + 1));
            File currentFile = fileList.get(i);

            if (currentFile.exists() && currentFile.isFile() && copyPathFile.exists() && copyPathFile.isDirectory()) {
                try (FileInputStream fis = new FileInputStream(currentFile);
                     FileOutputStream fos = new FileOutputStream(new File(copyPathFile, currentFile.getName()));
                     FileChannel sourceChannel = fis.getChannel();
                     FileChannel destinationChannel = fos.getChannel()) {
                    destinationChannel.transferFrom(sourceChannel, 0, sourceChannel.size());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }


            try {
                String fileExt = FileUtil.getFileExt(currentFile.getName());
                FileHandler handler = FileHandlerFactory.getInvokeStrategy(fileExt);
                List<String> imagPaths = handler.handleFile(currentFile.getAbsolutePath(), outputPath);
                if (CollectionUtils.isEmpty(imagPaths)){
                    continue;
                }
                // 本地通用转化测试
//                List<String> imgPathList = PdfUtil.pdf2img(fileList.get(i), outputPath);
                List<String> base64List = new ArrayList<>();

                // pdf 转 图片得到图片路径集合
                for (int j = 0; j < imagPaths.size(); j++) {
                    String base64 = FileUtil.fileToBase64(imagPaths.get(j));
                    base64List.add(base64);
                }

                // 发送请求
                HashMap<String, Object> params = new HashMap<>();
                params.put("docType", "Doc003");
                params.put("imgs", base64List);
                String param = JSON.toJSONString(params);
                HttpRequest httpRequest = HttpUtil.createPost("http://172.18.26.222:36036/hex/nlpapi/doc_extra");
                // 设定请求头
                httpRequest.header(Header.CONTENT_TYPE, "application/json");
                // 设定请求体
                httpRequest.body(param);
                String res = httpRequest.execute().body();
                res = convertUnicodeToChinese(res);
                JSONObject jsonObject = JSON.parseObject(res);


                //解析json结果
                ResultDataFGKDZ data = FileUtil.analysisResult(fileList.get(i), jsonObject);
                data = Optional.ofNullable(data).orElse(new ResultDataFGKDZ());
                resultList.add(data);
            } catch (Exception e) {
            }
            log.info("=================开第{}个文件处理完毕===================", (i + 1));
        }

        long endTime = System.currentTimeMillis();
        System.out.println("共耗时：" + ((endTime - startTime) / 1000.0) + "秒");  //转化用时
        ExcelUtil.generateExcel(exportPath, resultList);
    }

    // 将ASCII码转换为中文
    public static String convertUnicodeToChinese(String unicodeStr) {
        StringBuilder sb = new StringBuilder();
        int length = unicodeStr.length();

        for (int i = 0; i < length; i++) {
            char c = unicodeStr.charAt(i);

            if (c == '\\') {
                if (i < length - 1 && unicodeStr.charAt(i + 1) == 'u') {
                    String hexStr = unicodeStr.substring(i + 2, i + 6);
                    int charValue = Integer.parseInt(hexStr, 16);
                    sb.append((char) charValue);
                    i += 5;
                } else {
                    sb.append(c);
                }
            } else {
                sb.append(c);
            }
        }

        return sb.toString();
    }


    // 兴全获取某单据json报文
    public void newInterface(){
//        File currentFile = new File("E:\\文档\\工作\\文件测试\\ceshi\\7dbd3bb7967b4f9fba45c3cddc172683.pdf");
        String base64 = FileUtil.fileToBase64("E:\\文档\\工作\\文件测试\\ceshi\\7dbd3bb7967b4f9fba45c3cddc172683.pdf");
// 发送请求
        HashMap<String, Object> params = new HashMap<>();
        params.put("docType", "Doc003");
        params.put("pdf", base64);
        String param = JSON.toJSONString(params);
        HttpRequest httpRequest = HttpUtil.createPost("http://172.18.26.222:36036/hex/nlpapi/doc_extra");
        // 设定请求头
        httpRequest.header(Header.CONTENT_TYPE, "application/json");
        // 设定请求体
        httpRequest.body(param);
        String res = httpRequest.execute().body();
        res = convertUnicodeToChinese(res);
        JSONObject jsonObject = JSON.parseObject(res);
    }
}
